package com.pcitc.transfer.filter;


import cn.hutool.core.util.StrUtil;
import com.pcitc.transfer.util.JwtUtils;
import com.pcitc.transfer.util.ServletUtils;
import com.pcitc.transfer.util.TokenConstants;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 网关鉴权
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered
{
    private static final Logger log = LoggerFactory.getLogger(AuthFilter.class);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain)
    {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpRequest.Builder mutate = request.mutate();

        if(true){   //临时测试
            return chain.filter(exchange);
        }


        String url = request.getURI().getPath();

        String token = getToken(request);
        if (StrUtil.isEmpty(token))  {
            return unauthorizedResponse(exchange, "令牌不能为空");
        }
        Claims claims = JwtUtils.parseToken(token);
        if (claims == null)  {
            return unauthorizedResponse(exchange, "令牌已过期或验证不正确！");
        }
//        String userkey = JwtUtils.getUserKey(claims);
//        boolean islogin = true;  //redis获取用户是否已过期
//        if (!islogin)   {
//            return unauthorizedResponse(exchange, "登录状态已过期");
//        }
        String userid = JwtUtils.getUserId(claims);
        String username = JwtUtils.getUserName(claims);
        if (StrUtil.isEmpty(userid) || StrUtil.isEmpty(username))  {
            return unauthorizedResponse(exchange, "令牌验证失败");
        }

        return chain.filter(exchange.mutate().request(mutate.build()).build());
    }


    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange, String msg)
    {
        log.error("[鉴权异常处理]请求路径:{}", exchange.getRequest().getPath());
        return ServletUtils.webFluxResponseWriter(exchange.getResponse(), msg, HttpStatus.UNAUTHORIZED.value());
    }

    /**
     * 获取请求token
     */
    private String getToken(ServerHttpRequest request)
    {
        String token = request.getHeaders().getFirst(TokenConstants.AUTHENTICATION);
        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (StrUtil.isNotEmpty(token) && token.startsWith(TokenConstants.PREFIX))
        {
            token = token.replaceFirst(TokenConstants.PREFIX, StrUtil.EMPTY);
        }
        return token;
    }

    @Override
    public int getOrder()
    {
        return -200;
    }
}